package nl.windgazer.facebook.components;

import javax.servlet.http.HttpServletRequest;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.BeforeRenderTemplate;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Path;
import org.apache.tapestry5.ioc.annotations.Inject;

/**
 * A currently undocumented old xfbml tag that allows you to show a
 * like box with css-tweaks.
 * To use this xfbml tag you don't require an API/APP key, this can
 * be used on any website by simply targetting the correct profile-id.
 * The id in question can be obtained by checking the links inside
 * facebook, they should have some long number to indicate your 'fan-page'.
 * 
 * Since I like a 'clean' look, the header is disabled by default (while
 * the facebook default is enabled). Also I've opted for a transparent
 * default.
 * 
 * @author mreuring
 *
 */
public class Fan extends XFBMLElement {

	//Injects and Persists

	@Inject
	@Path("facebooklikebox.css")
	private Asset fbcss;

	@Inject
	private HttpServletRequest _request;

	//Properties and Parameters

	@Parameter(required = true, principal = false, defaultPrefix = BindingConstants.PROP, name = "profile_id")
	private String _profile_id;

	@Parameter(required = false, principal = false, defaultPrefix = BindingConstants.PROP, name = "header")
	private boolean _header = false;

	@Parameter(required = false, principal = false, defaultPrefix = BindingConstants.PROP, name = "stream")
	private boolean _stream = true;

	@Parameter(required = false, principal = false, defaultPrefix = BindingConstants.PROP, name = "transparent")
	private boolean _transparent = true;

	@Parameter(required = false, principal = false, defaultPrefix = BindingConstants.PROP, name = "connections")
	private Integer _connections = 6;

	@Parameter(required = false, principal = false, defaultPrefix = BindingConstants.PROP, name = "css")
	private Asset _css = null;

	@Parameter(required = false, principal = false, defaultPrefix = BindingConstants.PROP, name = "n")
	private Integer _n = 0;
	//Components

	//Events

	@BeforeRenderTemplate
	void renderXFBMLComment() {
		setTag("fan");
		setAttribs("profile_id", _profile_id, "header", String.valueOf(_header), "stream", String.valueOf(_stream), "transparent", String.valueOf(_transparent), "connections", _connections.toString(), "css", getFbcss());
	}

	//Other (check for business-logic, it should not remain here)

	public String getFbcss() {
		final StringBuffer sb = new StringBuffer(_request.isSecure()?"https://":"http://");
		sb.append(_request.getServerName());
		if (_request.getServerPort()!=80) {
			sb.append(':');
			sb.append(_request.getServerPort());
		}
		sb.append(_request.getContextPath());
		sb.append((_css==null?fbcss:_css).toClientURL());
		if (_n>0) {
			sb.append("?t=");
			sb.append(_n);
		}
		return sb.toString();
	}

}
